<template>
    <div class="goods-add-form">
        <div class="section">
            <h2 class="section-title">基础信息</h2>
            <el-form ref="ruleFormRef" style="max-width: 1200px;margin: 20px;" :model="data" status-icon
                :rules="rules" label-width="auto" class="demo-ruleForm">
                <el-form-item label="采购入库单号" prop="pb_code">
                    <el-input v-model="data.pb_code" placeholder="采购入库单号" disabled />
                </el-form-item>
                <div style="display: flex; justify-content: space-between;">
                    <div style="width: 48%;">
                        <el-form-item label="关联采购单号" style="margin-bottom: 30px;">
                            <el-input v-model="data.po_code" placeholder="关联采购单号" disabled />
                        </el-form-item>
                        <el-form-item label="供应商名称" style="margin-bottom: 30px;">
                            <el-input v-model="data.vendor_name" placeholder="供应商名称" disabled />
                        </el-form-item>
                        <el-form-item label="入库日期" prop="pb_Inboundtime" style="margin-bottom: 30px;">
                            <el-date-picker v-model="data.pb_Inboundtime" type="date" width="460"
                                placeholder="请选择入库日期" :size="size" style="width: 460px;" :editable="false"/>
                        </el-form-item>
                        <el-form-item label="操作人" style="margin-bottom: 30px;">
                            <el-input v-model="data.pb_operator" placeholder="操作人" disabled />
                        </el-form-item>
                    </div>

                    <div style="width: 48%;">
                        <el-form-item label="联系人" style="margin-bottom: 30px;">
                            <el-input v-model="data.contacts_name" placeholder="联系人" disabled />
                        </el-form-item>
                        <el-form-item label="联系方式" style="margin-bottom: 30px;">
                            <el-input v-model="data.contacts_phone" placeholder="联系方式" disabled />
                        </el-form-item>
                        <el-form-item prop="warehouse_code" label="入库仓库" style="margin-bottom: 30px;">
                            <el-select v-model="data.warehouse_code" placeholder="请选择入库仓库"
                                @change="handleSelectChange">
                                <el-option v-for="item in CKOptions" :key="item.warehouse_code"
                                    :label="item.warehouse_name" :value="item.warehouse_code" />
                            </el-select>
                        </el-form-item>
                        <el-form-item prop="zone_code" label="入库库区" style="margin-bottom: 30px;">
                            <el-select v-model="data.zone_code" placeholder="请选择入库库区" 
                                @change="handleSzone">
                                <el-option v-for="item in Warhouse_zone" :key="item.zone_code" 
                                :label="item.zone_name" :value="item.zone_code" />
                            </el-select>
                        </el-form-item>
                    </div>
                </div>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="data.remark" placeholder="请输入备注" />
                </el-form-item>
            </el-form>
        </div>

        <div class="section">
            <h2 class="section-title">入库产品明细</h2>
            <div style="float: left;margin: 10px 0px;">
                <el-button type="primary" @click="detailstAdd">添加</el-button>
                <el-button @click="productDel">移除</el-button>
            </div>
            <el-table :data="selectedData" border style="width: 100%" :cell-style="{ textAlign: 'center' }"
                :header-cell-style="{
                    textAlign: 'center',
                    background: '#f5f7fa',
                    fontWeight: 'bold',
                    position: 'sticky',
                    top: 0
                }" ref="selectedTable" @selection-change="handleSelectedChange">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="pro_name" label="货品名称" />
                <el-table-column prop="pro_code" label="货品编号" width="160" />
                <el-table-column prop="pro_brand" label="品牌" width="100" />
                <el-table-column prop="pro_model" label="规格型号" />
                <el-table-column prop="unitmeas_id" label="单位" width="70">
                    <template #default="scope">
                        <span>{{ measureValue(scope.row.unitmeas_id) }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="po_number" label="采购数量" />
                <el-table-column prop="details_monovalent" label="采购单价"/>
                <el-table-column prop="to_be_stored_qty" label="待入库数量">
                    <template #default="scope">
                            <span>{{DrkValue(scope.row)}}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="to_be_stored_qty" label="本次入库数量">
                    <template #default="scope">
                        <el-input v-model="scope.row.to_be_stored_qty" style="width: 75px" :precision="2" :min="0" @change="cfq" />
                    </template>
                </el-table-column>
                <el-table-column prop="details_storage" label="入库数量"/>
                <el-table-column prop="address" label="入库库位">
                    <template #default="scope">
                        <el-select v-model="scope.row.location_code" placeholder="选择库位" size="small"
                            @change="(val) => handleLocationChange(val, scope.row)">
                            <el-option v-for="item in Warehouse_location" :key="item.location_code"
                                :label="item.location_name" :value="item.location_code" />
                        </el-select>
                    </template>
                </el-table-column>
            </el-table>
            <div style="height: 40px; line-height: 40px;">
                <div style="display: inline-block; float: left;">合计</div>
                <div style="display: inline-block; float:right">入库总数量：{{ storage_total_qty }} &nbsp;&nbsp;&nbsp; 入库总额：{{
                        Number(storage_total_price).toFixed(2) }}
                </div>
            </div>
        </div>

        <div class="button-group" style="position: absolute; bottom: 10px; right: 64px; display: flex; gap: 10px;">
            <el-button @click="handleAdd">保存</el-button>
            <el-button @click="handleClose">关闭</el-button>
        </div>

        <!-- 添加明细对话框 -->
        <el-dialog v-model="proDetailsTableVisible" width="850" title="添加入库明细">
            <hr>
            <div style="margin: 10px 0px;">
                <div style="float: left;margin: 10px 0px;">
                    <el-input v-model="productName" style="width: 240px;margin-right: 20px;" placeholder="请输入产品编号/名称" />
                    <el-select v-model="dict_code" placeholder="请选择单位" style="width: 240px">
                        <el-option v-for="item in measureOptios" :key="item.dict_value" :label="item.dict_label"
                            :value="item.dict_value" />
                    </el-select>
                </div>
                <div style="float: right;margin: 10px 0px;">
                    <el-button @click="detalisReaslt">重置</el-button>
                    <el-button type="primary" @click="detailsEedit">
                        查询
                    </el-button>
                </div>
            </div>
            <el-table ref="multipleTableDetailsRef" :data="detailsData" :cell-style="{ textAlign: 'center' }"
                :header-cell-style="{
                    textAlign: 'center',
                    background: '#f5f7fa',
                    fontWeight: 'bold',
                    position: 'sticky',
                    top: 0
                }" @selection-change="handleSelectedChange" >
                <el-table-column type="selection" width="55" :selectable="isDisabled" />
                <el-table-column prop="pro_name" label="产品名称" />
                <el-table-column prop="pro_code" label="产品编号" width="160" />
                <el-table-column prop="pro_brand" label="品牌" width="100" />
                <el-table-column prop="pro_model" label="规格型号" />
                <el-table-column prop="unitmeas_id" label="单位" width="70">
                    <template #default="scope">
                        <span>{{ measureValue(scope.row.unitmeas_id) }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="po_number" label="采购数量" />
                <el-table-column prop="details_storage" label="待入库数量" >
                    <template #default="scope">
                        <span>{{ DrkValue(scope.row) }}</span>
                    </template>
                </el-table-column>
            </el-table>
            <br>
            <div style="text-align: center;display: flex; justify-content: center;">
                <el-pagination v-model:current-page="detailsCurrentPage" v-model:page-size="detailsPageSize"
                    :page-sizes="[5, 10, 20, 50]" :small="false" :background="true"
                    layout="total, sizes, prev, pager, next, jumper" :total="detailsPageCount"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" size="small" />
            </div>
            <hr>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleConfirmDetailsClose">取消</el-button>
                    <el-button type="primary" @click="handleConfirmDetailsSelection">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import { ref, reactive, onMounted, inject, watch } from 'vue'
import dayjs from 'dayjs'
import axios from 'axios'
import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import { debounce } from 'lodash';
import { useStore } from 'vuex';

export default {
    setup() {
        const store = useStore()
        const datamax = store.state.PO_UpdeteArray

        const data = reactive({
            pb_id: "",
            pb_code: "",
            po_id: "",
            po_code: "",
            vendor_name: "",
            vendor_code: "",
            contacts_name: "",
            contacts_phone: "",
            pb_Inboundtime: "",
            pb_operator: localStorage.getItem('userLName'),
            warehouse_code: "",
            zone_code: "",
            location_code:"",
            pb_Audit: "0",
            remark: "",
            del_flag: "0",
            update_by: localStorage.getItem('userLName'),
            update_time: dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ')
        });

        const ruleFormRef = ref(null);
        const rules = reactive({
            pb_code: [
                { required: true, message: "入库单号不能为空", trigger: "blur" },
            ],
            pb_Inboundtime: [
                { required: true, message: "入库日期不能为空", trigger: "blur" },
            ]
        });

        const Router = useRouter();
        // const route = useRoute();
        // let datamax = {};
        
        // // 解码URI组件
        // const decodedData = decodeURIComponent(route.query.datamax);
                
        // // 解析JSON
        // datamax = JSON.parse(decodedData);

        const CKOptions = ref([]);
        const selectedData = ref([]);
        const storage_total_qty = ref(0);
        const storage_total_price = ref(0);
        const Warhouse_zone = ref([]);
        const Warehouse_location = ref([]);
        const measureOptios = ref([]);
        const proDetailsTableVisible = ref(false);
        const productName = ref("");
        const dict_code = ref("");
        const detailsData = ref([]);
        const detailsCurrentPage = ref(1);
        const detailsPageSize = ref(5);
        const detailsPageCount = ref(0);
        const selectedTable = ref(null);
        const multipleTableDetailsRef = ref(null);
        const selectedDetailesRows = ref([]);
        
        function DrkValue(row){
            const sun = row.po_number-row.details_storage
            return sun
        }
        
        // 初始化数据
        async function initData() {
            Object.keys(datamax).forEach(key => {
                if (key in data) {
                    data[key] = datamax[key];
                }
            });
            
            if (datamax.details && Array.isArray(datamax.details)) {
                selectedData.value = datamax.details.map(item => {
                    const storage = item.details_storage || 0;
                    return {
                        ...item,
                        details_storage: storage,
                        to_be_stored_qty: item.to_be_stored_qty || 0
                    };
                });
                // console.log(selectedData.value)
            } else {
                console.warn("没有找到明细数据或明细数据格式不正确");
                selectedData.value = [];
            }
        }
        
        // 获取仓库选项
        function getCK() {
            axios.get("http://localhost:5181/api/Db_warehouse/WarehouseBySelect", {
                headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                CKOptions.value = result.data;
                // console.log(datamax.warehouse_code)
                // console.log(datamax.zone_code) 
                handleSzone(datamax.zone_code);
                handleSelectChange(datamax.warehouse_code);
            }).catch((err) => {
                console.error('获取仓库列表失败:', err);
                ElMessage.error('获取仓库列表失败');
            });
        }
        
        // 获取计量单位
        function getMeasure() {
            axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
                params: {
                    dict_type: "db_measure"
                }, 
                headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                measureOptios.value = result.data;
            }).catch((err) => {
                console.error('获取计量单位失败:', err);
            });
        }
        
        // 根据计量单位ID获取名称
        function measureValue(row) {
            if (!row) return "无";
            const measure = measureOptios.value.find(item => item.dict_value == row);
            return measure ? measure.dict_label : "无";
        }

        //选择仓库触发库区
        const handleSelectChange  = async (selectedValue) => {
            const selectedItem = CKOptions.value.find(item => item.warehouse_code === selectedValue);

            await axios.get("http://localhost:5181/api/Db_warehouse_zone/warehouse_zone", {
                params: {
                    warehouse_code: selectedValue
                }, headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                Warhouse_zone.value = result.data;
            })
        };
        
        //选择库区触发库位
        const handleSzone = async (value) => {
            const selectedItemzone = Warhouse_zone.value.find(item => item.zone_code === value);

            await axios.get("http://localhost:5181/api/Db_warehouse_location/warehouse_location", {
                params: {
                    zone_code: value
                }, headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                Warehouse_location.value = result.data;
            }).catch((err) => {
                console.info(err)
            })
        }
        
        const handleLocationChange = (value, row) => {
            const selectedLocation = Warehouse_location.value.find(item => item.location_code == value);
            if (selectedLocation) {
                row.location_code = selectedLocation.location_code;
            } else {
                row.location_code = "";
            }
        };
        
        // 加载明细数据
        const loadDetailsData = async () => {
            try {
                const result = await axios.get("http://localhost:5181/api/Po/GetdetailswherecodeFY", {
                    params: {
                        currentPage: detailsCurrentPage.value,
                        pageSize: detailsPageSize.value,
                        code: data.po_code,
                        procode: productName.value,
                        unitmeas_id: dict_code.value || 0
                    },
                    headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
                });

                detailsData.value = result.data.map(item => ({
                    ...item,
                    unfulfilled_qty: (Number(item.po_number || 0) - Number(item.details_storage || 0)),
                    to_be_stored_qty: 0
                }));

            } catch (err) {
                console.error('加载明细数据失败:', err);
                ElMessage.error('加载明细数据失败');
            }
        };

        // 加载明细总数
        const loadDetailsCount = async () => {
            try {
                const result = await axios.get("http://localhost:5181/api/Po/GetdetailswherecodeFYCount", {
                    params: {
                        code: data.po_code,
                        procode: productName.value,
                        unitmeas_id: dict_code.value || 0
                    },
                    headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
                });
                detailsPageCount.value = result.data;
            } catch (err) {
                console.error('加载明细总数失败:', err);
            }
        };

        // 合并查询和计数
        const fetchDetailsData = async () => {
            await Promise.all([loadDetailsData(), loadDetailsCount()]);
        };

        // 添加明细按钮点击事件
        const detailstAdd = () => {
            proDetailsTableVisible.value = true;
            fetchDetailsData();
        };

        // 明细查询按钮
        const detailsEedit = () => {
            fetchDetailsData();
        };

        // 明细重置按钮
        const detalisReaslt = () => {
            productName.value = "";
            dict_code.value = "";
            fetchDetailsData();
        };

        // 明细对话框取消按钮
        const handleConfirmDetailsClose = () => {
            proDetailsTableVisible.value = false;
            productName.value = "";
            dict_code.value = "";
        };

        // 表格选择变化时处理数据
        const handleSelectedChange = (val) => {
            selectedDetailesRows.value = val;
        };

        // 判断已添加过的产品数据不能再次添加
        const isDisabled = (row) => {
            return !selectedData.value.some(item => item.pro_code === row.pro_code);
        };

        // 移除选中的table控件数据
        const productDel = () => {
            if (selectedDetailesRows.value.length === 0) {
                ElMessage.warning('请先选择要移除的数据');
                return;
            }

            const selectedCodes = selectedDetailesRows.value.map(item => item.pro_code);
            selectedData.value = selectedData.value.filter(
                item => !selectedCodes.includes(item.pro_code)
            );

            selectedTable.value?.clearSelection();
            selectedDetailesRows.value = [];
        };

        // 点击确定保存选中的明细数据
        const handleConfirmDetailsSelection = () => {
            const newItems = selectedDetailesRows.value.map(item => ({
                ...item,
                location_code: "",
                to_be_stored_qty: 0
            }));

            selectedData.value = [
                ...selectedData.value,
                ...newItems.filter(newItem =>
                    !selectedData.value.some(existItem =>
                        existItem.pro_code === newItem.pro_code
                    )
                )
            ];
            
            multipleTableDetailsRef.value?.clearSelection();
            handleConfirmDetailsClose();
        };

        // 保存数据
        function handleAdd() {
            ruleFormRef.value.validate(async (valid) => {
                if (valid) {
                    if (selectedData.value.length === 0) {
                        ElMessage.warning('请填写入库产品明细');
                        return;
                    }
                    
                    const hasEmptyLocation = selectedData.value.some(item => !item.location_code);
                    if (hasEmptyLocation) {
                        ElMessage.warning('请为所有产品选择库位');
                        return;
                    }
                    
                    updateInbound();
                }
            });
        }

        watch(selectedData, (newVal) => {
            storage_total_qty.value = 0
            storage_total_price.value = 0
            newVal.forEach(row => {
                if (isNaN(Number(row.to_be_stored_qty))) {
                    ElMessage.warning('入库数量必须是数字');
                    row.to_be_stored_qty = 0;
                }
                const sun = row.po_number-row.details_storage
                if(row.to_be_stored_qty>sun){
                    ElMessage.warning('入库数量不可大于待入库数量');
                    row.to_be_stored_qty = sun
                }
                storage_total_qty.value += Number(row.to_be_stored_qty)
                storage_total_price.value += Number(row.to_be_stored_qty)*Number(row.details_monovalent).toFixed(2)
            })
        },{deep:true})
        
        // 更新入库单
        function updateInbound() {
            // alert(123)
            console.log(selectedData.value)
            const inboundDetailsDto = selectedData.value.map(item => ({
                pb_id: data.pb_id,
                purwhsedetail_id: item.purwhsedetail_id,
                to_be_stored_qty: item.to_be_stored_qty,
                location_code: item.location_code,
                pb_code:item.pb_code,
                pro_code: item.pro_code,
                pro_brand: item.pro_brand,
                pro_model: item.pro_model,
                unitmeas_id: item.unitmeas_id,
                details_monovalent: item.details_monovalent,
                po_number: item.po_number,
                pro_name: item.pro_name
            }));

            const InboundOrderDetailsDto = {
                inbound_Order_Dto: {
                    pb_id: data.pb_id,
                    Po_code: data.po_code,
                    pb_Inboundtime: data.pb_Inboundtime.replace(' ', 'T') + '.000Z',
                    pb_operator: localStorage.getItem('userLName'),
                    warehouse_code: data.warehouse_code,
                    zone_code: data.zone_code,
                    remark: data.remark,
                    update_by: localStorage.getItem('userLName'),
                    update_time: dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ'),
                },
                inbound_detailsDto: inboundDetailsDto
            };

            const postData = {
                Pb_Update_Dto: InboundOrderDetailsDto.inbound_Order_Dto,
                pbdetailsUpdateDtos: InboundOrderDetailsDto.inbound_detailsDto
            };
            
            axios.put("http://localhost:5181/api/Pb/PutPbUpdate", postData, {
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                if (result.data > 0) {
                    ElMessage({
                        type: 'success',
                        message: '采购入库单修改成功！'
                    });
                    handleClose();
                } else {
                    ElMessage.warning('未更新任何数据');
                }
            }).catch((err) => {
                console.error('更新入库单失败:', err);
                ElMessage.error('更新入库单失败: ' + (err.response?.data?.message || err.message));
            });
        }
        
        // 关闭页面
        const closeTab = inject('closeTab');
        function handleClose() {
            const targetPath = "/main/Pinv/Pb";

            if (closeTab) {
                closeTab();
            }

            const tabs = inject('editableTabs');
            if (tabs && !tabs.value.some(tab => tab.path === targetPath)) {
                tabs.value.push({
                    title: "采购入库",
                    name: targetPath,
                    path: targetPath
                });
            }

            const activeTab = inject('editableTabsValue');
            if (activeTab) {
                activeTab.value = targetPath;
            }

            Router.push(targetPath);
        }

        // 分页变化处理
        const handleSizeChange = (val) => {
            detailsPageSize.value = val;
            fetchDetailsData();
        };

        const handleCurrentChange = (val) => {
            detailsCurrentPage.value = val;
            fetchDetailsData();
        };

        onMounted(async() => {
            await initData();
            getCK();
            
            getMeasure();
            
            if (data.po_code) {
                fetchDetailsData();
            }
        });

        return {
            data,
            CKOptions,
            selectedData,
            storage_total_qty,
            storage_total_price,
            ruleFormRef,
            rules,
            Warhouse_zone,
            Warehouse_location,
            handleLocationChange,
            handleSzone,
            measureValue,
            handleAdd,
            handleClose,
            DrkValue,
            handleSelectChange,
            // 明细相关
            proDetailsTableVisible,
            productName,
            dict_code,
            detailsData,
            detailsCurrentPage,
            detailsPageSize,
            detailsPageCount,
            detailstAdd,
            detailsEedit,
            detalisReaslt,
            handleConfirmDetailsClose,
            handleSelectedChange,
            isDisabled,
            productDel,
            handleConfirmDetailsSelection,
            selectedTable,
            multipleTableDetailsRef,
            measureOptios,
            handleSizeChange,
            handleCurrentChange
        }
    }
}
</script>

<style scoped>
.goods-add-form {
    padding: 20px;
    background-color: #fff;
    margin-top: -40px;
}

.section {
    margin-bottom: 30px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 20px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    margin-top: -20px;
}

.section-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 15px;
}

.button-group {
    float: right;
    display: flex;
    position: flex;
    text-align: right;
    margin-top: 20px;
    height: 7%;
    align-items: center;
    width: 80.1%;
    background-color: #ffffff;
    justify-content: flex-end;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    padding-right: 20px;
}
</style>